package com.toymate.ai.tts.model.aliyun;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nls.client.AccessToken;
import com.alibaba.nls.client.protocol.NlsClient;
import com.alibaba.nls.client.protocol.OutputFormatEnum;
import com.alibaba.nls.client.protocol.SampleRateEnum;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizer;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizerListener;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizerResponse;
import com.toymate.ai.tts.AbstractTtsService;
import com.toymate.ai.tts.TtsConfig;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Optional;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * AliyunSttService
 *
 * @author weirdor (179946422@qq.com)
 * @version v1.0.0
 */
@Slf4j
public class AliyunTtsService extends AbstractTtsService {

    private static final Lock lock = new ReentrantLock();
    private static StringBuffer fileUrl = new StringBuffer();
    private NlsClient client;


    public AliyunTtsService(TtsConfig config) {
        this.config = config;
    }


    public static String generateFilePath() {
        lock.lock();
        try {
            String tmpDir = System.getProperty("java.io.tmpdir");
            String uniqueId = IdUtil.getSnowflakeNextIdStr();
            return tmpDir + uniqueId + ".mp3";
        } finally {
            lock.unlock();
        }
    }

    private static SpeechSynthesizerListener getSynthesizerListener(String filepath) {
        SpeechSynthesizerListener listener = null;
        try {
            listener = new SpeechSynthesizerListener() {
                File f = new File(filepath);
                FileOutputStream fout = new FileOutputStream(f);
                private boolean firstRecvBinary = true;

                // 语音合成结束
                @Override
                public void onComplete(SpeechSynthesizerResponse response) {
                    // 事件名称 SynthesisCompleted
                    //线程不安全如何返回str
                    fileUrl.append(f.getAbsolutePath());
                }

                @Override
                public void onFail(SpeechSynthesizerResponse response) {
                    //task_id是调用方和服务端通信的唯一标识，当遇到问题时需要提供task_id以便排查。
                    System.out.println(
                            "task_id: " + response.getTaskId() +
                                    //状态码 20000000 表示识别成功
                                    ", status: " + response.getStatus() +
                                    //错误信息
                                    ", status_text: " + response.getStatusText());
                    System.out.println("失败了");
                }

                // 语音合成的语音二进制数据
                @Override
                public void onMessage(ByteBuffer message) {
                    try {
                        if (firstRecvBinary) {
                            //计算首包语音流的延迟，收到第一包语音流时，即可以进行语音播放，以提升响应速度（特别是实时交互场景下）。
                            firstRecvBinary = false;
                            long now = System.currentTimeMillis();
                            //log.info("tts first latency : " + (now - NlsServiceImpl.startTime) + " ms");
                        }
                        byte[] bytesArray = new byte[message.remaining()];
                        message.get(bytesArray, 0, bytesArray.length);
                        fout.write(bytesArray);
                        //System.out.println(filepath);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };
        } catch (Exception e) {
            e.printStackTrace();
        }
        return listener;
    }

    /**
     * 文字转换语音
     *
     * @param content 转换的文字
     * @return Optional<String> 文件路径
     */
    @Override
    public Optional<String> speechSynthesizer(String id, String content) {
        String filePath = generateFilePath();
        SpeechSynthesizer synthesizer = null;
        try {
            String accessKeyId = config.getAliyunTtsConfig().getAccessKeyId();
            String accessKeySecret = config.getAliyunTtsConfig().getAccessKeySecret();
            String appKey = config.getAliyunTtsConfig().getAppKey();
            int volume = config.getAliyunTtsConfig().getVolume();
            String voiceId = config.getAliyunTtsConfig().getVoiceId();
            AccessToken accessToken = new AccessToken(accessKeyId, accessKeySecret);
            try {
                accessToken.apply();
                client = new NlsClient(accessToken.getToken());
            } catch (IOException e) {
                e.printStackTrace();
            }
            // Step1 创建实例,建立连接
            synthesizer = new SpeechSynthesizer(client, getSynthesizerListener(filePath));
            synthesizer.setAppKey(appKey);
            // 设置返回音频的编码格式
            synthesizer.setFormat(OutputFormatEnum.MP3);
            // 设置返回音频的采样率
            synthesizer.setSampleRate(SampleRateEnum.SAMPLE_RATE_16K);
            //发音人
            if (StrUtil.isNotEmpty(voiceId)) {
                synthesizer.setVoice(voiceId);
            }
            // 设置声音
            synthesizer.setVolume(volume);
            // 设置用于语音合成的文本
            synthesizer.setText(content);
            // Step2 此方法将以上参数设置序列化为json发送给服务端,并等待服务端确认
            synthesizer.start();
            // Step3 等待语音合成结束
            synthesizer.waitForComplete();
            return Optional.ofNullable(filePath);
        } catch (Exception e) {
            log.info("文字转换语音失败:{}", e.getMessage());
        } finally {
            // Step4 关闭连接
            if (null != synthesizer) {
                synthesizer.close();
            }
            //关闭连接
            shutdown();
        }
        return Optional.empty();
    }

    public void shutdown() {
        client.shutdown();
    }
}
